<?php

namespace Pm\Controllers;

use Admin\Models\pm\XhpmProjectTestRelateCase;
use Admin\Models\pm\XhpmProjectTest;
use Admin\Models\pm\XhpmProject;
use Helpers\Main;
use Helpers\Assets;
use Modules\Power;
use Helpers\User;
use Helpers\Template;

class TestController extends ControllerBase
{
    private static $levels = [
        1 => '普通',
        2 => '重要',
        3 => '紧急',
    ];

    private static $results = [
        1 => '未完成',
        2 => '成功',
        3 => '失败',
    ];

    /**
     * 测试用例列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180810
     */
    public function indexAction()
    {
        if (!Power::exist('Bpm_ProjectTest')) {
            return $this->sendViewError('权限不足', '无测试项目权限');
        }
        //获取项目id
        $iTestId = $this->request->getQuery('iTestId', 'int', 0);
        $iProjectId = $this->request->getQuery('iProjectId', 'int', 0);
        $re = $this->checkTestListPower($iProjectId, $iTestId);
        if (!$re) {
            return $this->sendViewError('该测试不存在');
        }
        $testName = '';
        if ($iTestId) {
            $test = XhpmProjectTest::findFirst($iTestId);
            $testName = $test->sName;
        }
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/test/testList.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $this->view->setVars([
            'levels' => self::$levels,
            'results' => self::$results,
            'testId' => $iTestId,
            'projectId' => $iProjectId,
            'testName' => $testName,
            'testAdd' => Power::exist('Bpm_ProjectTest_Add'),
            'testEdit' => Power::exist('Bpm_ProjectTest_Edit'),
            'testDel' => Power::exist('Bpm_ProjectTest_Del'),
            'caseEdit' => Power::exist('Bpm_ProjectTest_RelateCase_Edit'),
            'caseAdd' => Power::exist('Bpm_ProjectTest_RelateCase_Add'),
            'caseDel' => Power::exist('Bpm_ProjectTest_RelateCase_Del'),
        ]);
        $this->view->pick('test/testList');
    }

    /**
     * 项目测试用例列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180810
     */
    public function getCasesAction()
    {
        try {
            if (!Power::exist('Bpm_ProjectTest_RelateCase')) {
                return $this->sendErrorResponse('500', '权限不足', '无项目测试用例权限');
            }
            $iActualResult = $this->request->getPost('iActualResult', 'int');
            //获取项目id
            $iTestId = $this->request->getPost('iTestId', 'int', 0);
            $iProjectId = $this->request->getPost('iProjectId', 'int', 0);
            $re = $this->checkTestListPower($iProjectId, $iTestId);
            if (!$re) {
                return $this->sendViewError('该测试不存在');
            }
            $test = XhpmProjectTest::findFirst([
                'columns' => 'iId',
                'conditions' => "bDelete = 0 AND iId = $iTestId",
            ]);
            if (!$test) {
                return $this->sendJsonResponse([]);
            }
            $level = $this->request->getPost('level', 'int'); //根据任务等级筛选
            $condition = "c.bDelete = 0 AND c.iTestId = $iTestId";
            $condition .= $iActualResult && in_array($iActualResult, [0, 1, 2])
                ? " AND c.iActualResult = $iActualResult " : "";
            $condition .= $level && in_array($level, [1, 2, 3]) ? " AND c.iLevel = $level " : '';
            $builder = $this->modelsManager->createBuilder()
                ->columns("c.iId,c.sCode,c.sModule,c.sSubmodule,c.sFunctionPoint,c.iLevel,c.sPrecondition,
                 c.sSteps,c.sExpectedResult,c.iActualResult,c.sDefectNumber,c.tCreateDate,c.tLastModifyDate,s.sStaffName,c.sRemarks")
                ->addFrom('Admin\Models\pm\XhpmProjectTestRelateCase', 'c')
                ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'c.iCreateUserId = s.iUserId', 's')
                ->where($condition);
            $data = Main::runBuilderPages($builder, true);
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }

    /**
     * editCase表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180418
     */
    public function caseFormAction()
    {
        $iId = $this->request->getQuery('iId', 'int');
        if ($iId) {
            if (!Power::exist('Bpm_ProjectTest_RelateCase_Edit')) {
                return $this->sendViewError('权限不足', '无编辑项目测试用例权限');
            }
        } else {
            if (!Power::exist('Bpm_ProjectTest_RelateCase_Add')) {
                return $this->sendViewError('权限不足', '无新增项目测试用例权限');
            }
        }
        Assets::easyUI();
        Assets::select2();
        Assets::datetimePicker();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/test/caseForm.js');
        $this->view->setVars([
            'iId' => $iId,
            'levels' => self::$levels,
        ]);
        $this->view->pick('test/caseForm');
    }

    /**
     * 新建/编辑case
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180418
     */
    public function saveCaseAction()
    {
        $iId = $this->request->getPost('iId', 'int');
        $userId = Main::getLoginUserInfo('userId');
        try {
            $this->db->begin();  //开启事务
            if ($iId) {
                if (!Power::exist('Bpm_ProjectTest_RelateCase_Edit')) {
                    return $this->sendErrorResponse(500, '权限不足', '无编辑权限');
                }
                $case = XhpmProjectTestRelateCase::findFirst([
                    'conditions' => "iId = $iId AND bDelete = 0 AND iCreateUserId = $userId "
                ]);
                if (!$case || (!User::isAdmin())) {
                    return $this->sendErrorResponse(500, '编辑失败', '非创建人');
                }
                if ($case->iActualResult == 2 || $case->iActualResult == 3) {
                    return $this->sendErrorResponse(500, '编辑失败', '该用例已完成');
                }
            } else {
                if (!Power::exist('Bpm_ProjectTest_RelateCase_Add')) {
                    return $this->sendErrorResponse(500, '权限不足', '无任务创建权限');
                }
                $case = new XhpmProjectTestRelateCase();
            }
            $case->assign($this->request->getPost());
            $result = $case->save();
            if (!$result) {
                $this->db->rollback();
                return $iId ? $this->sendErrorResponse(500, '编辑失败')
                    : $this->sendErrorResponse(500, '创建失败');
            }
            $this->db->commit();
            return $iId ? $this->sendSuccessResponse('编辑成功') : $this->sendSuccessResponse('创建成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $iId ? $this->sendErrorResponse(500, '编辑失败', $exception->getMessage())
                : $this->sendErrorResponse(500, '创建失败', $exception->getMessage());
        }
    }

    /**
     * 获取已存在的case
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180813
     */
    public function getCaseInfoAction()
    {
        try {
            if (!Power::exist('Bpm_ProjectTest_RelateCase_Edit')) {
                return $this->sendErrorResponse(500, '权限不足', '无编辑权限');
            }
            $iId = $this->request->getPost('iId', 'int');
            if (!$iId) {
                return $this->sendErrorResponse(400, '参数错误', '无相关测试用例');
            }
            $caseInfo = XhpmProjectTestRelateCase::findFirst([
                'conditions' => 'bDelete=0 AND iId = :iId:',
                'bind' => array('iId' => $iId),
            ]);
            $caseInfo = $caseInfo ? $caseInfo->toArray() : [];
            return $this->sendJsonResponse($caseInfo);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取任务信息失败', $exception->getMessage());
        }
    }

    /**
     * 更改用例状态sucess or fail
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * modify by zqk 20180813
     */
    public function changeStatusAction()
    {
        if (!Power::exist('Bpm_ProjectTest_RelateCase_Edit')) {
            return $this->sendErrorResponse(500, '权限不足', '权限不足');
        }
        $userId = Main::getLoginUserInfo('userId');
        $iId = $this->request->getPost('iId', 'int');
        $result = $this->request->getPost('iActualResult', 'int');
        $remarks = $this->request->getPost('remarks');
        try {
            $this->db->begin(); //开启事务
            $case = XhpmProjectTestRelateCase::findFirst([
                'conditions' => "iId = $iId AND bDelete = 0"
            ]);
            if (!$case) {
                return $this->sendErrorResponse(500, '操作失败', '项目测试用例不存在');
            }
            $creatorId = $case->iCreateUserId;
            if (($creatorId != $userId && !User::isAdmin())) {
                return $this->sendErrorResponse(500, '操作失败', '非项目测试用例创建者');
            }
            $case->iActualResult = $result;
            $case->sRemarks = $remarks;
            $re = $case->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败', '修改状态失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 删除用例
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180816
     */
    public function delCaseByIdAction()
    {
        if (!Power::exist('Bpm_ProjectTest_RelateCase_Del')) {
            return $this->sendErrorResponse(500, '权限不足', '无删除权限');
        }
        $iId = $this->request->getPost('iId', 'int');
        try {
            $caseObj = XhpmProjectTestRelateCase::findFirst([
                'conditions' => "bDelete = 0 AND iId = $iId"
            ]);
            if (!$caseObj) {
                return $this->sendErrorResponse(400, '参数错误', '删除目标不存在');
            }
            $this->db->begin();
            $caseObj->bDelete = 1;
            $re = $caseObj->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    /**
     * 项目列表双击跳转到任务验证
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180601
     */
    public function checkTestListPowerAction()
    {
        $iProjectId = $this->request->get('iProjectId', 'int');
        $iTestId = $this->request->get('iTestId', 'int');
        $re = $this->checkTestListPower($iProjectId, $iTestId);
        if ($re) {
            return $this->sendSuccessResponse('验证成功');
        } else {
            return $this->sendErrorResponse(500, '验证失败', '无关联产品或项目不存在');
        }
    }

###################################################  测试列表  ######################################################

    /**
     * 获取测试列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180820
     */
    public function getTestsAction()
    {
        try {
            if (!Power::exist('Bpm_ProjectTest')) {
                return $this->sendErrorResponse(500, '无项目测试权限');
            }
            $iProjectId = $this->request->getPost('iProjectId', 'int');
            $re = $this->checkTestListPower($iProjectId, 0);
            if (!$re) {
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
            }
            $condition = "bDelete = 0 AND iProjectId = $iProjectId";
            $builder = $this->modelsManager->createBuilder()
                ->columns("iId,sName,iProjectId")
                ->addFrom('Admin\Models\pm\XhpmProjectTest')
                ->where($condition)
                ->orderBy("iId desc");
            $data = Main::runBuilderPaginator($builder, true);
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());

        }
    }

    /**
     * 新建/编辑 测试表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180810
     */
    public function testFormAction()
    {
        $iProjectId = $this->request->getQuery('iProjectId', 'int');
        $iTestId = $this->request->getQuery('iTestId', 'int');
        $re = $this->checkTestListPower($iProjectId, $iTestId);
        if (!$re) {
            return $this->sendViewError('参数错误');
        }
        if ($iTestId) {
            if (!Power::exist('Bpm_ProjectTest_Add')) {
                return $this->sendViewError('无编辑项目测试权限');
            }
        } else {
            if (!Power::exist('Bpm_ProjectTest_Edit')) {
                return $this->sendViewError('无编辑项目测试权限');
            }
        }
        Assets::easyUI();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/test/testForm.js');
        $this->view->setVars([
            'iProjectId' => $iProjectId,
            'iTestId' => $iTestId,
        ]);
        $this->view->pick('test/testForm');
    }

    /**
     * 新建/编辑项目测试
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180810
     */
    public function saveTestAction()
    {
        $iTestId = $this->request->getPost('iTestId', 'int');
        $sName = $this->request->getPost('sName');//名称
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        $re = $this->checkTestListPower($iProjectId, $iTestId);
        if (!$re) {
            return $this->sendErrorResponse('400', '参数错误');
        }
        try {
            $this->db->begin();  //开启事务
            if ($iTestId) {
                if (!Power::exist('Bpm_ProjectTest_Edit')) {
                    return $this->sendErrorResponse('500', '无编辑项目测试权限');
                }
                $testInfo = XhpmProjectTest::findFirst([
                    'conditions' => "iId != $iTestId AND iProjectId = $iProjectId AND sName = '" . $sName . "' AND bDelete = 0",
                ]);
                if ($testInfo) {
                    return $this->sendErrorResponse(400, $sName . '已存在');
                }
                $test = XhpmProjectTest::findFirst($iTestId);
                if (!$test) {
                    return $this->sendErrorResponse(400, '参数错误！');
                }
            } else {
                if (!Power::exist('Bpm_ProjectTest_Add')) {
                    return $this->sendErrorResponse('500', '无编辑项目测试权限');
                }
                $testInfo = XhpmProjectTest::findFirst([
                    'conditions' => "iProjectId = $iProjectId AND sName = '" . $sName . "' AND bDelete = 0",
                ]);
                if ($testInfo) {
                    return $this->sendErrorResponse(400, $sName . '已存在');
                }
                $test = new XhpmProjectTest();
            }
            $test->assign($this->request->getPost());
            $result = $test->save();
            if (!$result) {
                $this->db->rollback();
                return $iTestId ? $this->sendErrorResponse(500, '编辑失败') : $this->sendErrorResponse(500, '创建失败');
            }
            $this->db->commit();
            return $iTestId ? $this->sendSuccessResponse('编辑成功') : $this->sendSuccessResponse('创建成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $iProjectId ?
                $this->sendErrorResponse(500, '编辑失败', $exception->getMessage()) :
                $this->sendErrorResponse(500, '创建失败', $exception->getMessage());
        }
    }

    /**
     * 获取已存在的test
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180813
     */
    public function getTestInfoAction()
    {
        try {
            if (!Power::exist('Bpm_ProjectTest_Edit')) {
                return $this->sendErrorResponse(500, '权限不足', '无编辑权限');
            }
            $iId = $this->request->getPost('iTestId', 'int');
            if (!$iId) return $this->sendErrorResponse(400, '参数错误', '无相关项目测试');
            $testInfo = XhpmProjectTest::findFirst([
                'conditions' => 'bDelete=0 AND iId = :iTestId:',
                'bind' => array('iTestId' => $iId),
            ]);
            $caseInfo = $testInfo ? $testInfo->toArray() : [];
            return $this->sendJsonResponse($caseInfo);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取任务信息失败', $exception->getMessage());
        }
    }

    /**
     * 删除测试
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180810
     */
    public function delTestByIdAction()
    {
        if (!Power::exist('Bpm_ProjectTest_Del')) {
            return $this->sendErrorResponse(500, '权限不足', '无删除权限');
        }
        $iTestId = $this->request->getPost('iTestId', 'int');
        try {
            $testObj = XhpmProjectTest::findFirst([
                'conditions' => "bDelete = 0 AND iId = $iTestId"
            ]);
            if (!$testObj) {
                return $this->sendErrorResponse(400, '参数错误', '删除目标不存在');
            }
            $this->db->begin();
            $testObj->bDelete = 1;
            $re = $testObj->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    /**
     * 检查项目id是否合法权限 判断项目ID是否合法(跳转验证)
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180810
     */
    private function checkTestListPower($projectId, $testId)
    {
        if (!$projectId) {
            return false;
        }
        $condition = "bDelete = 0 AND iProjectId = $projectId AND (iProjectGrade = 2 OR iProjectGrade = 3)";   //版本或者模块
        $pids = $this->getProjectIds();
        if (!$pids && !User::isAdmin()) {
            return false;
        }
        $projectObj = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where($condition);
            if (!User::isAdmin()) {
                $projectObj ->inWhere("iProjectId", $pids);
            }
            $arr = $projectObj->getQuery()->execute()->toArray();
        if (!$arr) {
            return false;
        }
        if ($arr) {
            if (!$arr[0]['iProductId']) {
                return false;
            }
        }
        if ($testId) {
            $test = XhpmProjectTest::findFirst([
                'columns' => 'iId',
                'conditons' => "bDelete = 0 AND iProjectId = $projectId AND iId = $testId",
            ]);
            if (!$test) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取可以查看的项目ids
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180601
     */
    private function getProjectIds()
    {
        $deps = User::getextrapower('dep', 'project');  //获取扩展部门权限
        $uids = [];
        if ($deps) {
            $deps = implode(",%' OR  sDepIds like '%,", $deps);
            $conditions = 'bDelete = 0';
            $conditions .= " AND (sDepIds like '%," . $deps . ",%' ) ";
            $users = $this->modelsManager->createBuilder()
                ->columns("iUserId")
                ->From('Admin\Models\hrm\XhhrmStaff')
                ->where($conditions)
                ->getQuery()
                ->execute()
                ->toArray();
            foreach ($users as $k => $user) {
                $uids[] = $user['iUserId'];
            }
        }
        $userId = Main::getLoginUserInfo('userId');
        array_push($uids, $userId);
        $uids = array_unique($uids);
        $projectIds = $this->modelsManager->createBuilder()
            ->columns("iProjectId")
            ->addFrom('Admin\Models\pm\XhpmProjectMember')
            ->where("bDelete = 0")
            ->inwhere('iUserId', $uids)
            ->groupBy('iProjectId')
            ->getQuery()
            ->execute()
            ->toArray();
        $pids = [];
        foreach ($projectIds as $projectId) {
            $pids[] = $projectId['iProjectId'];
        }
        return $pids;
    }

    /**
     * productTestCases 列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180810
     */
    public function productTestCasesAction()
    {
        if (!Power::exist('Bpm_ProjectTest_RelateCase_Add')) {
            return $this->sendViewError('无新增项目测试用例权限');
        }
        $iProjectId = $this->request->getQuery('iProjectId', 'int');
        $iTestId = $this->request->getQuery('iTestId', 'int');
        $re = $this->checkTestListPower($iProjectId, $iTestId);
        if (!$re) {
            return $this->sendViewError('参数错误');
        }
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/test/testCaseList.js');
        $this->view->setVars([
            'iProjectId' => $iProjectId,
            'iTestId' => $iTestId,
        ]);
        $this->view->pick('test/testCaseList');
    }

    /**
     * 获取产品测试用例列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180810
     */
    public function getProductTestCasesAction()
    {
        if (!Power::exist('Bpm_ProjectTest_RelateCase_Add')) {
            return $this->sendErrorResponse(500, '权限不足');
        }
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        $iTestId = $this->request->getPost('iTestId', 'int');
        $re = $this->checkTestListPower($iProjectId, $iTestId);
        if (!$re) {
            return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
        }
        $sSubmodule = $this->request->getPost('sSubmodule', 'string');//模块名称搜索
        $project = XhpmProject::findFirst([
            'conditions' => "bDelete = 0 AND iProjectId = $iProjectId"
        ]);
        $iProductId = $project->iProductId;
        if (!$iProductId) {
            return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
        }
        $conditions = 'bDelete = 0';
        $conditions .= $sSubmodule ? " AND sSubmodule Like '%$sSubmodule%'" : '';
        $conditions .= " AND iProductId = $iProductId";
        $builder = $this->modelsManager->createBuilder()
            ->columns("iId,sCode,sModule,sSubmodule,sFunctionPoint")
            ->From('Admin\Models\pm\XhpmTestCase')
            ->where($conditions);
        $datas = Main::runBuilderPaginator($builder, true);
        return $this->sendJsonResponse($datas);
    }

    /**
     * 获取已选择的用例id
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180816
     */
    public function getCheckedCasesAction()
    {
        $iTestId = $this->request->getPost('iTestId', 'int');
        $conditions = "bDelete = 0 AND iTestId = $iTestId";
        //为传递类型
        $ids = XhpmProjectTestRelateCase::find([
            'columns' => 'iTestCaseId',
            'conditions' => $conditions,
        ])->toArray();
        if (!$ids) {
            return $this->sendJsonResponse([]);
        }
        $ids = array_unique(array_column($ids, 'iTestCaseId'));
        return $this->sendJsonResponse($ids);
    }

    /**
     * 批量添加case
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180520
     */
    public function addMultiCaseAction()
    {
        if (!Power::exist('Bpm_ProjectTest_RelateCase_Add')) {
            return $this->sendErrorResponse(500, '权限不足', '无新增权限');
        }
        $iTestId = $this->request->getPost('iTestId', 'int');
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        $re = $this->checkTestListPower($iProjectId, $iTestId);
        if (!$re) {
            return $this->sendErrorResponse('500', '该测试不存在');
        }
        $test = XhpmProjectTest::findFirst([
            'conditions' => "bDelete = 0 AND iId = $iTestId"
        ]);
        if (!$test) {
            return $this->sendErrorResponse(500, '项目测试不存在');
        }
        $iIds = $this->request->getPost('iIds') ? $this->request->getPost('iIds') : [];//传递过来的
        $iIds = array_unique($iIds);
        $conditions = "bDelete = 0 AND iTestId = $iTestId";
        //为传递类型
        $testCaseIds = XhpmProjectTestRelateCase::find([
            'columns' => 'iTestCaseId',
            'conditions' => $conditions,
        ])->toArray();
        $testCaseIds = array_unique(array_column($testCaseIds, 'iTestCaseId'));
        $addIds = array_diff($iIds, $testCaseIds);
        $delIds = array_diff($testCaseIds, $iIds);
        //任务创建人id  && name
        try {
            $testCases = $this->modelsManager->createBuilder()
                ->addFrom('Admin\Models\pm\XhpmTestCase')
                ->where('bDelete = 0')
                ->inWhere("iId", $addIds)
                ->getQuery()
                ->execute()
                ->toArray();
            $this->db->begin();
            foreach ($testCases as $testCase) {
                $testCaseObj = new XhpmProjectTestRelateCase();
                $testCaseObj->assign($testCase);
                $testCaseObj->iId = null;
                $testCaseObj->iTestCaseId = $testCase['iId'];
                $testCaseObj->iTestId = $iTestId;
                $re = $testCaseObj->save();
                if (!$re) {
                    $this->db->rollBack();
                    return $this->sendErrorResponse(500, '操作失败');
                }
            }
            if ($delIds) {
                $res = $this->modelsManager->executeQuery("update \\Admin\\Models\\pm\\XhpmProjectTestRelateCase set bDelete = 1 where iTestCaseId in ({delIds:array})", ['delIds' => $delIds]);
                if (!$res) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '审核失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

}

